package cn.sharp.bbs.service.impl;

import cn.sharp.bbs.dao.InteractDao;
import cn.sharp.bbs.dao.gen.CollectpostMapper;
import cn.sharp.bbs.dao.gen.FollowpostMapper;
import cn.sharp.bbs.dao.gen.LikeMapper;
import cn.sharp.bbs.entity.DO.Collectpost;
import cn.sharp.bbs.entity.DO.Followpost;
import cn.sharp.bbs.entity.DO.Like;
import cn.sharp.bbs.event.CollectEvent;
import cn.sharp.bbs.event.PostLikeEvent;
import cn.sharp.bbs.service.InteractService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Transactional
public class InteractServiceImpl implements InteractService , ApplicationEventPublisherAware {
    private ApplicationEventPublisher eventPublisher;

    @Resource
    private InteractDao interactDao;

    @Resource
    private LikeMapper likeMapper;

    @Resource
    private CollectpostMapper collectpostMapper;

    @Resource
    private FollowpostMapper followpostMapper;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.eventPublisher = applicationEventPublisher;
    }
    @Override
    public void likePost(Long postId, Long u_id) {
        if (interactDao.checkIsLike(postId, u_id) > 0) {
            interactDao.cancelLike(postId, u_id);
        } else {
            Like like = new Like();
            like.setPostId(postId);
            like.setUserId(u_id);
            like.setTime(new Date());
            likeMapper.insert(like);

            eventPublisher.publishEvent(new PostLikeEvent(this,like.getId()));
        }
    }

    @Override
    public void collectPost(Long postId, Long u_id) {
        if (interactDao.checkIsCollect(postId, u_id) > 0) {
            interactDao.cancelCollect(postId, u_id);
        } else {
            Collectpost collectpost = new Collectpost();
            collectpost.setPostId(postId);
            collectpost.setUserId(u_id);
            collectpost.setTime(new Date());
            collectpostMapper.insert(collectpost);

            eventPublisher.publishEvent(new CollectEvent(this,collectpost.getId()));
        }
    }

    @Override
    public void followPost(Long postId, Long u_id) {
        if (interactDao.checkIsFollow(postId, u_id) > 0) {
            interactDao.cancelFollow(postId, u_id);
        } else {
            Followpost followpost = new Followpost();
            followpost.setPostId(postId);
            followpost.setUserId(u_id);
            followpost.setTime(new Date());
            followpostMapper.insert(followpost);
        }
    }


}
